<template>
	<div class="factoryModeling-page">
		<div class="factoryModeling-page-search">
			<el-input
				class="search-input"
				v-model="searchData.productLineName"
				placeholder="请输入生产线名称"
				clearable></el-input>
			<!-- <el-button class="search-button ml-10 mt-10" type="primary" @click="getTableData"
				>搜索</el-button
			>
			<el-button class="reset-button mt-10" type="warning" @click="reset">重置</el-button> -->
			<SearchOrReset @getTableData="getTableData" @reset="reset"></SearchOrReset>
		</div>
		<div class="factoryModeling-page-funcBtns">
			<el-button class="funcBtns-add mt-10" type="primary" @click="openDialog">
				新增
			</el-button>
		</div>
		<div class="factoryModeling-page-table mt-10">
			<PublicTable :table-data="tableData" :table-header="columnObj">
				<template #controls="{row,index}">
					<edit-or-del @edit="edit(row.id)" @del="del(row.id)">
					</edit-or-del>
				</template>
			</PublicTable>
		</div>
		<div class="factoryModeling-page-paging mt-10">
			<el-pagination
				:page-sizes="[5, 10, 15, 20]"
				layout="total, sizes, prev, pager, next, jumper"
				:current-page="pageNum"
				:page-size="pageSize"
				:total="total"
				@size-change="pageSizeChange"
				@current-change="pageNumChange">
			</el-pagination>
		</div>
		<el-dialog
			:title="dialogTitle"
			:visible.sync="dialogVisible"
			width="50%"
			@close="closeDialog">
			<el-form :model="form" :rules="rulesForProduct" ref="form" label-width="100px">
				<el-form-item label="生产线名称：" prop="productLineName">
					<el-input
						placeholder="请输入生产线名称"
						v-model="form.productLineName"></el-input>
				</el-form-item>
				<el-form-item label="产品：" prop="product">
					<el-input
						placeholder="请输入产品"
						:disabled="isDisabled"
						v-model="form.product"></el-input>
					<el-button type="primary" @click="getMaterialFile">选择</el-button>
				</el-form-item>
				<el-form-item label="产品型号：" prop="productNumber">
					<el-input
						placeholder="请输入产品型号"
						:disabled="isDisabled"
						v-model="form.productNumber"></el-input>
				</el-form-item>
				<el-form-item label="产品规格：" prop="productSpecifications">
					<el-input
						placeholder="请输入产品规格"
						:disabled="isDisabled"
						v-model="form.productSpecifications"></el-input>
				</el-form-item>				
				<el-form-item label="描述：" prop="remark">
					<el-input placeholder="请输入描述" v-model="form.remark"></el-input>
				</el-form-item>
			</el-form>
			<el-divider>
				<span>设备明细信息</span>
			</el-divider>
			<el-dropdown
				class="deviceSelect"
				trigger="click"
				type="primary"
				placement="top-start"
				@command="deviceSelect">
				<el-button type="primary">
					添加<i class="el-icon-arrow-down el-icon--right"></i>
				</el-button>
				<el-dropdown-menu slot="dropdown">
					<el-dropdown-item
						v-for="(item, index) in deviceData"
						:key="item.id"
						:command="item.id">
						{{ item.equipmentName }}
					</el-dropdown-item>
				</el-dropdown-menu>
			</el-dropdown>
			<el-table :data="deviceSelectData" border stripe class="mt-10">
				<el-table-column label="序号" prop="id" width="35" align="center"></el-table-column>
				<el-table-column label="设备" prop="equipmentName" align="center"></el-table-column>
				<el-table-column
					label="编号"
					prop="equipmentNumber"
					align="center"></el-table-column>
				<el-table-column label="型号" prop="equipmentSize" align="center"></el-table-column>
				<el-table-column
					label="生产日期"
					prop="equipmentCreatTime"
					align="center"></el-table-column>
				<el-table-column label="生产批号" prop="productId" align="center"></el-table-column>
				<el-table-column
					label="制造商"
					prop="productPeople"
					align="center"></el-table-column>
				<el-table-column label="操作" align="center">
					<template slot-scope="scope">
						<el-button type="danger" @click="deviceDelete(scope.row.id)"
							>删除</el-button
						>
					</template>
				</el-table-column>
			</el-table>

			<span slot="footer">
				<el-button @click="closeDialog">取消</el-button>
				<el-button type="primary" @click="save">确定</el-button>
			</span>
			<!-- 内层dialog -->
			<el-dialog
				title="选择物料档案"
				:visible.sync="dialogVisible1"
				width="50%"
				append-to-body
				custom-class="dialogMaterial">
				<div class="selectMaterialFile">
					<div class="selectMaterialFile-classification">
						<el-tree :data="treeData" :props="defaultProps" @node-click="nodeClick">
						</el-tree>
					</div>
					<div class="selectMaterialFile-materialList">
						<el-table :data="materialFileAll" max-height="500">
							<el-table-column
								label="编号"
								prop="id"
								align="center"></el-table-column>
							<el-table-column
								label="物料编码"
								prop="materielNumber"
								align="center"></el-table-column>
							<el-table-column
								label="物料名称"
								prop="materielName"
								align="center"></el-table-column>
							<el-table-column
								label="型号"
								prop="materielModelNumber"
								align="center"></el-table-column>
							<el-table-column
								label="规格单位"
								prop="unit"
								align="center"></el-table-column>
							<el-table-column
								label="单价"
								prop="price"
								align="center"></el-table-column>
							<el-table-column
								label="类型"
								prop="materielType"
								align="center"></el-table-column>
							<el-table-column
								label="备注"
								prop="remark"
								align="center"></el-table-column>
							<el-table-column
								label="操作"
								fixed="right"
								align="center"
								ref="buttonCol">
								<template slot-scope="scope">
									<el-button
										type="primary"
										:disabled="scope.row.clicked"
										@click="selectMaterial(scope.row, scope.$index)"
										>选择</el-button
									>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</div>
				<span slot="footer">
					<el-button @click="">取消</el-button>
					<el-button type="primary" @click="determineMaterials">确定</el-button>
				</span>
			</el-dialog>
		</el-dialog>
	</div>
</template>

<script>
import { getBaseData, saveData, deleteData, deleteDataS } from '@/api/Common';
import SearchOrReset from '@/components/Buttons/SearchOrReset.vue';
import PublicTable from '../../components/Tables/PublicTable.vue';
import EditOrDel from '../../components/Buttons/EditOrDel.vue';
export default {
	name: "FactoryModeling",
	components: {
		SearchOrReset,
		PublicTable,
		EditOrDel
	},
	data() {
		return {
			total: 5,
			pageNum: 1,
			pageSize: 5,
			tableData: [],//总表格数据
			columnObj: [],//总表格列
			deviceData: [], //设备
			deviceSelectData: [], //添加的设备
			searchData: {
				//搜索框数据
				productLineName: "",
			},
			dialogVisible: false,
			dialogVisible1: false,
			dialogTitle: "",
			form: {}, //提交的表单
			isDisabled: true,
			treeData: [
				{
					label: "分类",
					children: [
						{
							label: "零件",
						},
						{
							label: "成品",
						},
					],
				},
			],
			defaultProps: {
				children: "children",
				label: "label",
			},
			// 点击选择-查询到的所有物料档案
			materialFileAll: [],
			clickRows: {}, //记录被点击的按钮
			addDeviceVal: "", //添加设备的值
			factoryId: null, //产品主id
			rulesForProduct: {
				productLineName: [{ required: true, message: "请输入生产线名称", trigger: "blur" }],
				product: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
			},
		};
	},

	created() {
		this.getTableData();
	},

	methods: {
		// getButtons() {
		// 	let buttonIndexes = this.$refs.buttonCol.querySelectorAll("button");
		// 	let buttonIndexesArray = Array.from(buttonIndexes).map((btn) =>
		// 		Array.prototype.indexOf.call(this.$refs.buttonCol.children, btn)
		// 	);
		// 	console.log(buttonIndexesArray);
		// },
		// 获取表格数据
		getTableData() {
			let params = {
				pageNum: this.pageNum,
				pageSize: this.pageSize,
				productLineName: this.searchData.productLineName,
			}
			getBaseData("/factoryModeling/search", params).then((res) => {
				console.log("表格数据", res);
				if (res.code === "200") {
					this.tableData = res.data.list;
					this.total = res.data.total;
					this.setTableColumn()
				}
			})
				.catch((err) => {
					console.log(err);
				});
		},
		setTableColumn() {
			let tableData = this.tableData.map((item) => {
				let { id, product, productLineName } = item
				return { id, product, productLineName }
			})
			//设置所需数据所需的键
			let columns = tableData[0]
			console.log('columns', columns);
			//设置表格列的label
			const labelValues = ['编号', '产品', '生产线名称']
			// 生成一个新的数组，含有以下配置项
			let propArray = Object.keys(columns).map((key, index) => {
				return {
					prop: `${key}`,
					label: labelValues[index],
					align: 'center',
					width: '',
					text: true
				}
			})
			propArray[0].width = '50'
			//添加操作列
			propArray.push({
				prop: '',
				label: '操作',
				align: 'center',
				slot: 'controls'
			})
			this.columnObj = propArray
		},
		// 获取设备数据
		getDevice() {
			getBaseData("/deviceInformation/searchAll")
				.then((res) => {
					console.log("设备", res);
					if (res.code === "200") {
						this.deviceData = res.data;
					}
				})
				.catch((err) => {
					console.log(err);
				});
		},
		// 选择的设备
		deviceSelect(command) {
			// console.log(command);
			let deviceSelectData = this.deviceSelectData;
			// 选择的添加进数组
			deviceSelectData.push(this.deviceData[command - 1]);
			// console.log(this.deviceData);
			// debugger
			// 根据设备的id进行数组去重
			let deviceSelectDataS = deviceSelectData.filter((item, index, self) => {
				return self.findIndex((otItem) => otItem.id === item.id) === index;
			});
			// debugger

			this.deviceSelectData = deviceSelectDataS;
			this.generateIdsList()
			console.log('sb', this.deviceSelectData);
			console.log("选择的设备", this.form);
		},
		// 对deviceSelectData的删除操作
		deviceSelectDataDel(deviceId) {
			let idToDelDevice = this.deviceSelectData.findIndex((item) => item.id === deviceId);
			// debugger

			console.log('idToDelDevice', idToDelDevice);
			if (idToDelDevice !== -1) {
				// 删除对应id的设备
				this.deviceSelectData.splice(idToDelDevice, 1);
				console.log("deviceSelectData", this.deviceSelectData);

				// debugger
				// 创建一个新的idList
				this.generateIdsList()
			}
		},
		//删除选中的设备
		deviceDelete(id) {
			if (this.dialogTitle === "添加工厂建模") {
				this.deviceSelectDataDel(id);
			}
			console.log("选择的设备", this.form);
			if (this.dialogTitle === "修改工厂建模") {
				console.log(id);
				this.deviceSelectDataDel(id);
				let params = {
					factoryId: this.factoryId,
					deviceId: id,
				}
				deleteDataS("/factoryModeling/deleteDeviceInfo", params).then((res) => {
					console.log(res);
					if (res.code === "200") {
						this.$message.success("您已删除该设备！");
						console.log("delDevice", this.form);
						this.getProductToId(this.factoryId);
						// console.log('del',this.deviceSelectData);
					} else {
						console.log("删除失败！", this.form);
						this.$message.error("删除失败！");
					}
				})
					.catch((err) => {
						console.log("删除失败！", this.form);
						console.log(err);
					});
			}
		},
		// 选中物料
		selectMaterial(row, index) {
			this.clickRows = row;
			// console.log("按索引", scope,index);
			this.form = {
				// productLineName: "",
				product: row.materielName,
				productNumber: row.materielModelNumber,
				productSpecifications: row.unit,
				// remark: "",
			};
			// console.log(this.clickRows);
		},
		unDetermineMaterials() {
			this.form = {};
			this.dialogVisible1 = false;
		},
		determineMaterials() {
			// this.form = this.clickRows
			// console.log(this.form);
			this.dialogVisible1 = false;
		},
		// 保存
		save() {
			// console.log(this.form);
			// if (this.dialogTitle === "添加工厂建模") {
			// if ((this.form.productLineName !== "" && null) && (this.form.product !== "" || null)) {
			if (!this.form.productLineName || !this.form.product) {
				this.$message.warning("请填写完整！");
				// return false;
				console.log("填写不完整", this.form);
			} else {
				console.log("填写完整", this.form);
				saveData("/factoryModeling/addOrUpdateInfo", this.form)
					.then((res) => {
						console.log(res);
						if (res.code === "200") {
							this.$message.success("保存成功！");
							this.form = {};
							this.closeDialog();
							this.getTableData();
						} else {
							this.$message.error("保存失败！");
						}
					})
					.catch((err) => {
						console.log("err", this.form);
						console.log(err);
					});
			}

			// else {
			// 	console.log('填写不完整', this.form);
			// 	this.$message.warning("请填写完整！");
			// }
			// }
		},
		// 获取零件
		getPart() {
			getBaseData("/materialFile/searchParts").then((res) => {
				console.log("零件", res);
				if (res.code === "200") {
					this.materialFileAll = res.data;
					// this.getButtons()
				}
			});
		},
		// 获取成品
		getFinishedProduct() {
			getBaseData("/materialFile/searchFinishedProduct").then((res) => {
				if (res.code === "200") {
					this.materialFileAll = res.data;
					// this.getButtons()
				}
			});
		},
		// 获取tree点击的id
		nodeClick(res) {
			let treeId = res.$treeNodeId;
			if (treeId === 1) {
				getBaseData("/materialFile/searchAll")
					.then((res) => {
						if (res.code === "200") {
							this.materialFileAll = res.data;
						}
						console.log("物料档案all", this.materialFileAll);
					})
					.catch((err) => {
						console.log(err);
					});
			}
			if (treeId === 2) {
				this.getPart();
			}
			if (treeId === 3) {
				this.getFinishedProduct();
			}
		},
		// 点击选择-获取物料档案
		getMaterialFile() {
			this.dialogVisible1 = true;
			getBaseData("/materialFile/searchAll")
				.then((res) => {
					if (res.code === "200") {
						this.materialFileAll = res.data;
						// this.getButtons()
					}
					console.log("物料档案all", this.materialFileAll);
				})
				.catch((err) => {
					console.log(err);
				});
		},
		// 重置搜索
		reset() {
			this.searchData = {};
			this.getTableData();
		},
		pageSizeChange(pageSize) {
			this.pageSize = pageSize;
			this.getTableData();
		},
		pageNumChange(pageNum) {
			this.pageNum = pageNum;
			this.getTableData();
		},
		del(id) {
			debugger
			console.log(typeof(id));
			deleteDataS(`/factoryModeling/deleteInfo/${id}`)
				.then((res) => {
					debugger
					console.log(res);
					if (res.code === "200") {
						this.$message.success("删除成功！");
						this.getTableData();
					} else {
						this.$message.error("删除失败！");
					}
				})
				.catch((err) => {
					console.log(err);
				});
		},
		openDialog() {
			this.form = {};
			this.dialogTitle = "添加工厂建模";
			this.getDevice();
			this.dialogVisible = true;
		},
		closeDialog() {
			this.form = {};
			this.deviceSelectData = [];
			this.dialogVisible = false;
			this.getTableData();
		},
		// 点击修改按钮
		edit(factoryId) {
			this.dialogTitle = "修改工厂建模";
			this.dialogVisible = true;
			this.factoryId = factoryId;
			console.log(this.factoryId);
			this.getDevice();
			this.getProductToId(factoryId);
		},
		// 获取点击修改-的产品数据
		getProductToId(id) {
			if (id) {
				getBaseData("/factoryModeling/searchUpdatePage/" + id)
					.then((res) => {
						console.log("修改-的产品", res);
						this.form = res.data;
						this.deviceSelectData = res.data.deviceInfoList;
						this.generateIdsList();
					})
					.catch((err) => {
						console.log(err);
					});
			}
		},
		// 生成form里的idsList
		generateIdsList() {
			let idsList = this.deviceSelectData.map((item) => {
				return item.id;
			});
			this.form.idsList = idsList;
		},
	},
};
</script>

<style lang="scss" scoped>
.factoryModeling-page {
	.factoryModeling-page-search {
		display: flex;
		align-items: center;
		.search-input {
			width: 300px;
		}

		.search-button {}

		.ml-10 {}

		.mt-10 {}

		.reset-button {}
	}

	.factoryModeling-page-funcBtns {
		.funcBtns-add {}

		.mt-10 {}
	}

	.factoryModeling-page-table {}

	.factoryModeling-page-paging {
		text-align: center;
	}

	span {}

	.device {
		/deep/ .el-form-item__content {
			margin-left: 0 !important;
		}
	}
}
</style>
<style>
.dialogMaterial .selectMaterialFile {
	display: flex;
}

.dialogMaterial .selectMaterialFile-classification {
	width: 15%;
}

.dialogMaterial .selectMaterialFile-materialList {
	width: 85%;
}
</style>
